package com.itheima.service.Impl;


import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.dto.AddCategoryDto;
import com.itheima.dto.ModifyCategoryDto;
import com.itheima.mapper.CategoryMapper;
import com.itheima.pojo.Category;
import com.itheima.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public boolean AddCategory(AddCategoryDto dto) {
        if (Objects.isNull(dto)) {
            return false;
        }
        Category category = new Category();
        BeanUtils.copyProperties(dto, category);
        Snowflake snowflake = new Snowflake();
        String id = snowflake.nextIdStr();
        category.setId(id);
        LambdaQueryWrapper<Category> clqw = new LambdaQueryWrapper<>();
        clqw.eq(Category::getName, category.getName());
        List<Category> categories = categoryMapper.selectList(clqw);
        if (categories.size() != 0) {
            return false;
        }
        return categoryMapper.insertCategory(category) > 0;
    }

    @Override
    public boolean modifyCategory(ModifyCategoryDto dto) {
        if (Objects.isNull(dto)) {
            return false;
        }
        Category category = new Category();
        BeanUtils.copyProperties(dto, category);
        return categoryMapper.updateById(category) > 0;
    }

    @Override
    public boolean delById(String id) {
        return categoryMapper.deleteById(id) > 0;
    }

    @Override
    public List<Category> getCategory(){
        return categoryMapper.selectList(null);
    }

    @Override
    public Page<Category> getCategoryPage(Integer page, Integer pagesize){
        Page<Category> pg = new Page<>(page,pagesize);
        Page<Category> categoryPage = categoryMapper.selectPage(pg, null);
        return categoryPage;
    }

    @Override
    public long getCategoryIdByName(String name) {
        return categoryMapper.selectIdByName(name);
    }
}
